package com.northpool.operator.common.json;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSONObject;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.exception.ParamException;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

import java.util.Map;

@OperatorInfo(
        ref = "Xml2JsonOperator",
        name = "XML转JSON",
        description = "XML字符串转JSON字符串",
        version = "1.0.0"
)
@OutputParams({
        @OutputParam(ref = "result", name = "JSON", desc = "JSON字符串")
})
public class Xml2JsonOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "xml", name = "XML", desc = "XML字符串", type = TypeEnum.STRING, required = true)
    })
    public Xml2JsonOperator() {
    }

    public static void main(String[] args) {
        OperatorTestBuild.execute(Xml2JsonOperator.class, TestParamBuilder.aBuilder()
                .param("xml", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
                        "<xml xmlns=\"utf-8\">\n" +
                        "  <name>张三</name>\n" +
                        "  <age>18</age>\n" +
                        "</xml>\n")
                .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String xmlStr = paramTool.getStr("xml");
        if (StrUtil.isBlank(xmlStr)) {
            throw new ParamException("xml", "XML字符串不能为空");
        }

        Map<String, Object> map = XmlUtil.xmlToMap(xmlStr);
        String json = JSONObject.toJSONString(map);
        this.result("result", json);
    }
}
